#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import os
from google.appengine.ext.webapp import template
import yaml
from google.appengine.api import users
from google.appengine.ext import db
import logging
# New DAO
from transactionDao import *
from urlparse import urlparse


INDEX_HTML_PATH="web/afindex.html";
CONFIGURE_HTML_PATH="web/afconfigure.html";
RESULTS_HTML_PATH="web/afhistory.html";


# Get the target URL, without parameters, April 2012
# User by history and discover
def getTargetUrl(uri):
        targetUrl= uri.split('?');
        #logging.error(targetURl is %s  ,  targetUrl[0]);
        return targetUrl[0];

  
class MainHandler(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        # Commented Out
        #if user is None:
        #    self.redirect(users.create_login_url(self.request.uri))
            
        
        
        path = os.path.join(os.path.dirname(__file__), INDEX_HTML_PATH)
        templateValues = {
                    'ticker': "INTC",
                    'keyCount': 0,
                    'recommendation': "*** Please enter a valid Ticker ***",
            }
        #templateValues,count=getAllOptimalValuesFromDataStore()
        #count = int ( count )
        
        #if (count < 1):
        #        initialize("Growth")
        #        initialize("Income")
        #        initialize("Value")

        #templateValues,count=getAllOptimalValuesFromDataStore()
        initialize();
        logging.error('path is %s  ', path);
        self.response.out.write(template.render(path, templateValues))


class configure(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        # Commented out for now
        #if user is None:
        #    self.redirect(users.create_login_url(self.request.uri))

        path = os.path.join(os.path.dirname(__file__), CONFIGURE_HTML_PATH)
        templateValues = {
                    ticker: "INTC",
                    keyCount: 0,
                    recommendation: "*** Please enter a valid Ticker ***",
            }
        #templateValues,count=getAllOptimalValuesFromDataStore()
        self.response.out.write(template.render(path, templateValues))


   
class submitTicker(webapp.RequestHandler):
    def post(self):

               
        ticker=cgi.escape(self.request.get('ticker'))
        ticker= ticker.upper()
        logging.error('ticker is %s  ', ticker);
        
        page=self.request.get("page", default_value="1");
        page=int(page);
      
        templateValues=getAllTransaction(page, getTargetUrl(self.request.uri));
        
        path = os.path.join(os.path.dirname(__file__), RESULTS_HTML_PATH)
        self.response.out.write(template.render(path, templateValues))
        


class submitConfiguration(webapp.RequestHandler):
    def post(self):
   
        configType = cgi.escape(self.request.get(configType))
       
        path = os.path.join(os.path.dirname(__file__), INDEX_HTML_PATH)
        #templateValues,count=getAllOptimalValuesFromDataStore()
        templateValues = {
                    ticker: "INTC",
                    keyCount: 0,
                    recommendation: "*** Please enter a valid Ticker ***",
            }
        self.response.out.write(template.render(path, templateValues))



# Adds the Type to the DB. Needed for the first time
def initialize():
#        initializeStockAnalysis()
#        optimalValues=getOptimalValuesFromDataStore(type)
        
        # If OptimalValues are not found in DataStore then get from Configuration File.
#        if not ( optimalValues):      
          transaction = Transaction()
          if users.get_current_user():
            transaction.author = users.get_current_user()
          transaction.fraudFlag="N";
          transaction.amount= float ("100.00" );
        
          transaction.pan= "51234";
          transaction.mcc="5541";
          transaction.currencyCode="840";
          transaction.merchantName="QT STCH";
          #transaction.qRevGrowth=str ( getOptimalQRevGrowth()) 
          #transaction.divYield=str ( getOptimalYield() )
          #transaction.beta=str ( getOptimalBeta() )
          #transaction.configType= type
          transaction.put()
        

def main():
    application = webapp.WSGIApplication([('/', MainHandler),
                                          ('/configure', configure),
                                          ('/submitConfiguration', submitConfiguration),
                                          ('/submitTicker', submitTicker)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
